package com.tsinghua.server.base.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.tsinghua.server.config.jwt.JWTUtils;
import com.tsinghua.server.common.Result;
import com.tsinghua.server.base.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@RestController
@Slf4j
@Api(tags = {"登录系统"})
@RequiredArgsConstructor
@RequestMapping(value = "")
public class LoginController {


    private final UserService userService;


    /**
     * 获取token
     * @param loginForm
     * @return
     */
    @PostMapping("open/auth/token")
    @ApiOperation(value = "查询密码配置", notes = "查询密码配置")
    public Result doLogin(@RequestBody Map loginForm) {
        String username = (String)loginForm.get("username");
        String password = (String)loginForm.get("password");
        String verifyKey = (String)loginForm.get("verifyKey");
        String verifyCode = (String)loginForm.get("verifyCode");
        return Result.succ(userService.createToken(username,password,verifyKey,verifyCode));
    }


    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @GetMapping("/auth/getInfo")
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息接口")
    public Result getInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        JWTUtils.verify(token);
        DecodedJWT verify = JWTUtils.getTokenInfo(token);
        String userName = verify.getClaim("userName").asString();
        return Result.succ(userName);
    }

    @PostMapping("/auth/updatePass")
    @ApiOperation(value = "修改密码", notes = "修改密码接口")
    public Result resetPass(@RequestBody Map map,HttpServletRequest request) {
        return Result.succ(userService.updatePass(map,request));
    }

    @PostMapping("/auth/resetPass")
    @ApiOperation(value = "初始化密码", notes = "初始化密码接口")
    public Result resetPass(HttpServletRequest request) {
        return Result.succ(userService.resetPass(request));
    }


//    @PostMapping("/doLogout")
//    @ApiOperation(value = "登出", notes = "登出接口")
//    public CommonResult doLogout(HttpServletRequest request) {
//        doLoginService.doLogout(request);
//        return CommonResult.ok();
//    }

}
